package com.tai.design.responsibility.jdk;

import java.util.ArrayList;
import java.util.List;

/**
 * The type Filter chain.
 *
 * @version v1.0
 * @ClassName: FilterChain
 * @Description: TODO(一句话描述该类的功能)
 * @Author: taylor
 */
public class FilterChain { //过滤器链

    private List<Filter> filters = new ArrayList<Filter>();

    private int index = 0;

    /**
     * Add filter filter chain.
     *
     * @param filter the filter
     * @return the filter chain
     */
// 链式调用
    public FilterChain addFilter(Filter filter) {
        this.filters.add(filter);
        return this;
    }

    /**
     * Do filter.
     *
     * @param request  the request
     * @param response the response
     */
    public void doFilter(Request request, Response response) {
        if (index == filters.size()) {
            return;
        }
        Filter filter = filters.get(index);
        index++;
        filter.doFilter(request, response, this);
    }
}
